//
//  HWQQGameSearchController.swift
//  HWanGame
//
//  Created by 王昌健 on 2023/12/12.
//  Copyright © 2023 94hwan. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
class HWQQGameSearchController: HWBaseViewController {
    var searchBgView:UIView!
    var searchField:UITextField!
    var searchLogoImageView:UIImageView!
    var searchButton:UIButton!
    var tableView:UITableView!
    var tableViewProtocol = HWQQGameSearchProtocol()
    var httpManager = HWQQGameTypeHttpManager()
    var modelArr = NSMutableArray()
    var keyword = ""
    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        
        initFrame()
        
        addAction()
        
        addRefresh()
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        searchField.becomeFirstResponder()
    }

}
extension HWQQGameSearchController {
    private func initUI() -> Void {
        IQKeyboardManager.shared.shouldResignOnTouchOutside = true
        IQKeyboardManager.shared.enableAutoToolbar = false
        IQKeyboardManager.shared.enable = true
    
        navigationView.backButton.setImage(UIImage(named: "navBackButton"), for: .normal)
        
        searchBgView = UIView()
        searchBgView.backgroundColor = .white

        searchBgView.layer.cornerRadius = 17*widthScale
        searchBgView.layer.borderWidth = 1
        searchBgView.layer.borderColor = UIColor.colorWithHexString(hexString: "#EEEEEE").cgColor
        navigationView.addSubview(searchBgView)
        
        searchLogoImageView = UIImageView()
        searchLogoImageView.image = UIImage(named: "search");
        searchBgView.addSubview(searchLogoImageView)
        
        searchButton = UIButton(type: .custom)
        searchButton.setTitle("搜索", for: .normal)
        searchButton.setTitleColor(.colorWithHexString(hexString: "#333333"), for: .normal)
        searchButton.titleLabel?.font = .boldSystemFont(ofSize: 14*widthScale)
        searchButton.addTarget(self, action: #selector(searchButtonClick(_:)), for: .touchUpInside)
        navigationView.addSubview(searchButton)
        
        searchField = UITextField()
        searchField.font = UIFont.systemFont(ofSize: 14*widthScale)
        searchField.delegate = self
        searchField.returnKeyType = .search
        searchField.textColor = .colorWithHexString(hexString: "#333333")
        searchBgView.addSubview(searchField)
        
        let placeHoldLabel = UILabel.init()
        placeHoldLabel.text = "请输入关键字进行搜索"
        placeHoldLabel.textColor = UIColor.colorWithHexString(hexString: "#888888")
        placeHoldLabel.font = UIFont.systemFont(ofSize: 14*widthScale)
        searchField.setValue(placeHoldLabel, forKey: "_placeholderLabel")
        searchField.addTarget(self, action: #selector(searchTextFieldChange(_:)), for: .editingChanged)
        
        tableView = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        tableView.delegate = tableViewProtocol
        tableView.dataSource = tableViewProtocol
        tableView.backgroundColor = .colorWithHexString(hexString: "#FFFFFF")
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = UIScreen.main.bounds.size.height
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.showsVerticalScrollIndicator = false
        view.addSubview(tableView)
        tableView.contentInsetAdjustmentBehavior = .never
        self.tableView.isPagingEnabled = false
        tableView.scrollIndicatorInsets = tableView.contentInset
        tableView.ly_emptyView = LYEmptyView.empty(withImageStr: "", titleStr: "", detailStr: "暂无数据")
        tableView.ly_emptyView.contentViewOffset = -40
//        if #available(iOS 15.0, *) {
//            self.tableView.sectionHeaderTopPadding = 0
//        } else {
//            // Fallback on earlier versions
//        }
        
    }
    
    private func initFrame() -> Void {
        searchBgView.snp.makeConstraints { make in
            make.centerY.equalTo(navigationView.backButton)
            make.height.equalTo(34*widthScale)
            make.left.equalTo(navigationView.backButton.snp.right).offset(18*widthScale)
            make.width.equalTo(255*widthScale)
        }
        
        searchLogoImageView.snp.makeConstraints { make in
            make.left.equalTo(10*widthScale)
            make.width.height.equalTo(17*widthScale)
            make.centerY.equalToSuperview()
        }
        
        searchButton.snp.makeConstraints { make in
            make.right.equalTo(-18*widthScale)
            make.centerY.equalTo(searchBgView)
        }
        
        searchField.snp.makeConstraints { make in
            make.left.equalTo(searchLogoImageView.snp.right).offset(4*widthScale)
            make.height.equalTo(20*widthScale)
            make.centerY.equalToSuperview()
            make.right.equalTo(-18*widthScale)
        }
        
        tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(searchBgView.snp.bottom).offset(10*widthScale)
        }
        
    }
}
extension HWQQGameSearchController {
    func addRefresh() -> () {
//        tableView.mj_header = MJRefreshNormalHeader()
//        tableView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(self.searchWithKeyword))
        tableView.mj_footer = MJRefreshBackNormalFooter()
        tableView.mj_footer?.setRefreshingTarget(self, refreshingAction: #selector(self.loadMoreData))
        tableView.mj_footer?.isHidden = true
    }
    
    @objc func searchWithKeyword() -> Void {
        self.tableView.mj_footer?.resetNoMoreData()
        httpManager.getQQGameListHeader(sort: "", keyword: keyword) { models in
            self.tableViewProtocol.models = models
            if models.count > 0 {
                self.tableView.mj_footer?.isHidden = false
                self.modelArr.removeAllObjects()
                self.modelArr.addObjects(from: models)
            }
            self.tableView.reloadData()
        } failure: { error in
            self.view.showHUD(title: error)
            self.modelArr.removeAllObjects()
            self.tableView.reloadData()
            self.tableView.mj_footer?.isHidden = true
        }

    }
    
    @objc func loadMoreData() -> () {
        httpManager.getQQGameListFooter(sort: "", keyword: keyword) { models in
            self.tableView.mj_footer?.endRefreshing()
            if models.count > 0 {
                self.modelArr.addObjects(from: models)
            } else {
                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
            }
            self.tableViewProtocol.models = self.modelArr as? [HWQQGameListModel]
            self.tableView.reloadData()
        } failure: { error in
            self.tableView.mj_footer?.endRefreshing()
        }
        
    }
}

extension HWQQGameSearchController {
    func addAction() -> Void {
        tableViewProtocol.gameButtonClick = {
            mod in
            self.httpManager.getQQGameClickUpLoad(gameId: mod.appid) { success in
                
            } failure: { errorString in
                
            }
            QQMiniAppSDKManager.sharedInstance().showApplication(withAppID: mod.appid, scene: .MAEntrySceneNone, parentVC: self, hostModel: nil)
            
            let historyModel = HWQQGameHistoryListModel()
            historyModel.id = mod.id
            historyModel.name = mod.name
            historyModel.icon = mod.icon
            historyModel.content = mod.content
            historyModel.appid = mod.appid
            historyModel.type = mod.type
            historyModel.biaoqian = mod.biaoqian
            historyModel.time = mod.time
            
            //最多只显示五条最新数据
            if HWDataBaseManager.defaultManger.selectAll().count == 5 {
                HWDataBaseManager.defaultManger.deleteWithSql(sql: "id in (select id from QQGameHistory where userId = '\(HWLocallyStoredData.getLoginUserID())' order by id ASC limit 1)") {
                    
                } failBlock: {
                    
                }
                
            }
            HWDataBaseManager.defaultManger.delete(appId: historyModel.appid) {
                
            } failBlock: {
                
            }
            HWDataBaseManager.defaultManger.insert(appId:historyModel.appid, model: historyModel) {
                
            } failBlock: {
                
            }
        }
    }
}
extension HWQQGameSearchController:UITextFieldDelegate {
    @objc func searchTextFieldChange(_ textField:UITextField) ->Void {
        if textField.text?.count == 0 {
            keyword = ""
        }
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        textField.endEditing(true)
        keyword = textField.text ?? ""
        searchWithKeyword()
        return true
    }
    
    @objc func searchButtonClick(_:UIButton) -> Void {
        keyword = self.searchField.text ?? ""
        searchWithKeyword()
    }
}
